import axios from "axios";
import {message} from "ant-design-vue"

axios.defaults.timeout = 20000;
axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.headers['X-Requested-with'] = 'XMLHttpRequest';
axios.defaults.withCredentials = true;
import {
    replayDefence,
    encryptRequest,
    distortDefence,
    loading,
    removeLoading
} from './requestHandler'
class HttpRequest {

    constructor() {
        this.instance = axios.create();
        this.interceptors();
    }

    interceptors(){
        this.instance.interceptors.request.use((config) =>{
            config.headers['token'] = localStorage.getItem('token');

            if(config.url){
                replayDefence(config);
                // 报文加密
                encryptRequest(config);
                // 防篡改
                distortDefence(config);
                loading();
                return config;
            }
        }, error => {
            return Promise.reject(error);
        });

        this.instance.interceptors.response.use((res) => {
            removeLoading();
            if(res.data.code === 'renewal'){
                res.config.headers['token'] = res.data.data;
                localStorage.setItem('token', res.data.data);
                return this.instance(res.config);
            }else if(res.data.code === 'error'){
                message.error(res.data.message);
                return;
            }else if(res.data.code === 'authority'){
                localStorage.removeItem("token");
                window.location.href = "/";
                return;
            }

            return res.data;
        }, error => {
            return Promise.reject(error);
        })
    }

    post(url, data ={}){
        return this.instance.post(url, data);
    }

    get(url, data = {}){
        return this.instance.get(url, data);
    }

    put(url, data ={}){
        return this.instance({
            url: url,
            method: 'put',
            data: data
        })
    }

    delete(url, data = {}){
        return this.instance({
            url: url,
            method: 'delete',
            params: data
        })
    }

}

export default HttpRequest
